package tech.yangzhijie.basic.knowledge.other;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(10);
        CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo(countDownLatch);

        long start = System.currentTimeMillis();
        for (int i=0;i < 10;i++){
            new Thread(countDownLatchDemo).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("耗费时间为：" + (end - start));
    }
}

class CountDownLatchDemo implements Runnable{

    private CountDownLatch countDownLatch;

    public CountDownLatchDemo(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 500000; i++) {
                if(i % 2 == 0){
                    System.out.println(i);
                }
            }
        }finally {
            this.countDownLatch.countDown();
        }
    }
}
